# !/usr/bin/env python
# encoding: utf-8


"""
  @author: gaogao
  @file: e5080b_driver.py
  @time: 2021/5/19 15:58
  @desc:
"""
import pyvisa as visa
import serial


# 选择trace,更换window的序号
# display:window4:trace1:select
# 查找最大最小值的指令
# CALCulate<cnum>:MEASure<mnum>:MARKer<mkr>:FUNCtion:EXECute <func>
# 获得marker的y值
# calculate1:measure1:marker4:y?
# 获得marker的x值
# calculate1:measure1:marker4:x?


def init_visa(visa_address_in, timeout_in_ms=6000000):
    ena_inst = visa.ResourceManager().open_resource(visa_address_in)
    ena_inst.timeout = timeout_in_ms
    # visa.log_to_screen(10)
    return ena_inst


def reset(ena_session_in, debug_ena_in=False):
    write(ena_session_in=ena_session_in,
          ena_command_in="*RST",
          debug_ena_in=debug_ena_in)


def write(ena_session_in, ena_command_in, debug_ena_in=False):
    """
    Sends a Standard Commands for Programmable Instruments  command to the instrument defined by the SCPI session
    :param ena_session_in: The ENA session to send the command to
    :param ena_command_in:: The ENA command to send
    :param debug_ena_in: If True, # prints the sent command
    :return:
    """

    # # print the input if debug
    if debug_ena_in:
        print('Debug ENA Command Sent: ' + ena_command_in)
    # Add the newline
    ena_session_in.write(ena_command_in)
    return


def query(ena_session_in, query_command_in, debug_ena_in=False):
    if debug_ena_in:
        print("debug......")
    return ena_session_in.query(query_command_in)


def close(ena_session_in):
    ena_session_in.close()


class ENADriver:
    def __init__(self, visa_address_in, timeout_in_ms=6000000, connect_in=True, debug_ena_in=False):
        # Start a session
        self.__is_connected = False
        self.__visa_address = visa_address_in
        self.__timeout_in_ms = timeout_in_ms
        self.__debug_mode = debug_ena_in
        if connect_in:
            self.__ena_session = init_visa(
                visa_address_in=visa_address_in, timeout_in_ms=timeout_in_ms)
            self.__is_connected = True

    def get_marker_value(self, window_index_list):
        total_value_list = []
        for window_index in window_index_list:
            cmd = f"display:window{window_index}:trace1:select"
            write(self.__ena_session, cmd)
            if window_index == 1:
                cmd = f"calculate1:measure{window_index}:marker4:function:execute minimum"
            else:
                cmd = f"calculate1:measure{window_index}:marker4:function:execute maximum"
            write(self.__ena_session, cmd)
            y_value_list = []
            x_value_list = []
            for i in range(1, 5):
                if window_index == 3 or window_index == 4:
                    if i == 1:
                        cmd = f"calculate1:measure{window_index}:marker4:y?"
                        y_value = '{:.3f}'.format(float(self.query(cmd).strip().split(",")[0]))
                        y_value_list.append(y_value)
                else:
                    cmd = f"calculate1:measure{window_index}:marker{i}:y?"
                    y_value = '{:.3f}'.format(float(self.query(cmd).strip().split(",")[0]))
                    y_value_list.append(y_value)
                if i == 1:
                    if window_index == 1 or window_index == 2:
                        cmd = f"calculate1:measure{window_index}:marker4:x?"
                        x_value = '{:.3f}'.format(float(self.query(cmd).strip().split(",")[0]))
                        if x_value:
                            x_value_list.append(x_value)

            if x_value_list:
                y_value_list.extend(x_value_list)

            if y_value_list:
                total_value_list.append(y_value_list)
        return total_value_list

    def query(self, cmd):
        return query(self.__ena_session, cmd)

    def colse(self):
        close(self.__ena_session)
